import {createAsyncThunk, createSlice, PayloadAction} from "@reduxjs/toolkit";
import {LoginParams, UserInfo} from "@/type/userType";
import {userLoginAPI} from "@/api/userAPI/userAPI";
import {getStorage, removeStorage, setStorage} from "@/utils/storage";


interface State {
    userInfo: UserInfo
    isModalOpen: boolean
}

const initialState: State = {
    userInfo: getStorage() || {},
    isModalOpen: false
}

export const userLogin: any = createAsyncThunk("userLogin", async (loginParams: LoginParams, {dispatch}) => {
    try {
        const {data} = await userLoginAPI(loginParams)
        return data
    } catch (error: any) {
        return Promise.reject(new Error(error.message))
    }

})

const userStore = createSlice({
    name: "userStore",
    initialState,
    reducers: {
        setToken(state, action: PayloadAction<string>) {
            state.userInfo.token = action.payload
        },
        clearToken(state, action: PayloadAction<string>) {
            state.userInfo.token = action.payload
        },
        changeModalOpen(state, action: PayloadAction<boolean>) {
            state.isModalOpen = action.payload
        },
        clearUserInfo(state) {
            state.userInfo = {} as UserInfo
            removeStorage()
        }
    },
    extraReducers(builder) {
        builder.addCase(userLogin.pending, () => {

        }).addCase(userLogin.fulfilled, (state, action: PayloadAction<UserInfo>) => {
            state.userInfo = action.payload
            setStorage<UserInfo>(action.payload)
        }).addCase(userLogin.rejected, () => {

        })
    }

})


export const {changeModalOpen, clearUserInfo} = userStore.actions

export default userStore.reducer
